// 权限控制
import router, { asyncRoutes } from './router'
import store from './store'
import { getToken } from './utils/auth'
// 处理一级路由权限数据
function getFirstRoutePerms(permsArr) {
  if (permsArr.includes('*:*:*')) return ['*']
  const newArr = permsArr.map(item => {
    return item.split(':')[0]
  })
  return [...new Set(newArr)]
}
// 处理二级路由权限数据
// // 处理二级路由权限数据
function getSecondRoutePerms(permsArr) {
  if (permsArr.includes('*:*:*')) return ['*:*']
  const newArr = permsArr.map(item => {
    const arr = item.split(':')
    return `${arr[0]}:${arr[1]}`
  })
  return [...new Set(newArr)]
}
// // 根据权限标识过滤路由表
function getRoutes(firstRoutePerms, secondRoutePerms, asyncRoutes) {
  if (firstRoutePerms.includes('*') || secondRoutePerms.includes('*:*')) return asyncRoutes
  // 根据一级和二级对动态路由表做过滤 return出去过滤之后的路由表
  // 1. 根据一级路由对动态路由表做过滤
  return asyncRoutes.filter(route => {
    return firstRoutePerms.includes(route.permission)
  }).map(item => {
    // 2. 对二级路由做过滤
    return {
      ...item,
      children: item.children.filter(item => secondRoutePerms.includes(item.permission))
    }
  })
}
const WHITE_LIST = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  const token = getToken()
  // 有token
  if (token) {
    // 获取用户信息
    if (!store.state.user.profile.id) {
      // 1. 调用action函数获取用户权限数据
      const perms = await store.dispatch('user/getProfile')
      // 2. 把后端的权限数组格式化成我们自己的俩个权限数据
      console.log('当前的权限数据为:', perms)
      const firstRoutePerms = getFirstRoutePerms(perms)
      // console.log(firstRoutePerms)
      const secondRoutePerms = getSecondRoutePerms(perms)
      // console.log(secondRoutePerms)
      // // 3. 通过菜单权限过滤一级和二级得到权限菜单列表
      const filterRoutes = getRoutes(firstRoutePerms, secondRoutePerms, asyncRoutes)
      console.log('filterRoutes', filterRoutes)
      // 4. addRoute动态添加
      filterRoutes.forEach(route => router.addRoute(route))
      // 5. 存入Vuex渲染左侧菜单
      store.commit('user/setMenuList', filterRoutes)
    }
    next()
  } else {
    // 没有token
    console.log('没有token')

    if (WHITE_LIST.includes(to.path)) {
      next()
    } else {
      console.log('没有token--返回登录页')
      next('/login')
    }
  }
})
